#pragma once

#include <iostream>
#include <string>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "Util.hpp"

using namespace std;

const string sep = "\r\n";
const string defualt_root = "wwwroot";
const string home_page = "index.html";
const string html_404 = "wwwroot/html_404";

class HttpRequest
{
public:
    HttpRequest()
    {
    }
    ~HttpRequest()
    {
    }

    void prase()
    {
        // 1. 从inbuffer中拿到第一行，分隔符\r\n
        string line = Util::getOneline(inbuffer, sep);
        if (line.empty())
            return;

        // 2. 从请求行中提取三个字段
        stringstream ss(line);
        ss >> method >> url >> httpversion;

        // 3. 添加web默认路径
        path = defualt_root; // ./wwwroot,
        path += url;         //./wwwroot/a/b/c.html, ./wwwroot/
        if (path[path.size() - 1] == '/')
            path += home_page;

        // 4. 获取path对应的资源后缀
        // ./wwwroot/index.html
        // ./wwwroot/test/a.html
        // ./wwwroot/image/1.jpg
        auto pos = path.rfind(".");
        if (pos == string::npos)
            suffix = "html";
        else
            suffix = path.substr(pos);

        // 5. 得到资源的大小
        struct stat st;
        int n = stat(path.c_str(), &st);
        if (n == 0)
            size = st.st_size;
        else
            size = -1;
    }

public:
    string inbuffer;
    string method;
    string url;
    string httpversion;
    string path;
    string suffix;
    int size;
    string parm;
};

class HttpResponse
{
public:
    HttpResponse()
    {
    }
    ~HttpResponse()
    {
    }

public:
    string outbuffer;
};